package com.renzhichu.app.onelogin;


import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TabHost;
import android.widget.Toast;

import com.cmic.sso.sdk.AuthRegisterViewConfig;
import com.cmic.sso.sdk.utils.rglistener.CustomInterface;
import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.Promise;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.uimanager.PixelUtil;
import com.geetest.onelogin.OneLoginHelper;
import com.geetest.onelogin.config.OneLoginThemeConfig;
import com.geetest.onelogin.listener.AbstractOneLoginListener;
import com.renzhichu.app.MainActivity;
import com.renzhichu.app.R;

import org.json.JSONException;
import org.json.JSONObject;


public class OneLogin extends ReactContextBaseJavaModule implements ActivityCompat.OnRequestPermissionsResultCallback {
    /**
     * 日志 TAG
     */
    public static final String TAG = "OneLogin";
    private Activity context;

    /**
     * 返回状态为200则表示成功
     */
    public static final int ONE_LOGIN_SUCCESS_STATUS = 200;
    public static final int ONE_LOGIN_BACK_STATUS = 300;
    public static final int ONE_LOGIN_ERROR_STATUS = 500;

    public static final String CUSTOM_ID = "6b308c4f8d1d883cb72a138e7d4ee15e";


    public OneLogin(ReactApplicationContext reactContext) {
        super(reactContext);
        context = reactContext.getCurrentActivity();
    }


    @Override
    public String getName() {
        return "RNTOneLogin";
    }

    private Promise promise;
    private String agreementCustom;

    @ReactMethod
    public void sendMessage(String agreementCustom, Promise promise) {
        //先获取权限
        this.promise = promise;
        this.agreementCustom = agreementCustom;
        OneLoginHelper.with().init(this.getCurrentActivity());
        OneLoginHelper.with().setRequestedOrientation(this.getCurrentActivity(), true);
        preGetToken();
//        getPermission();
    }

    private final static int REQUEST_READ_PHONE_STATE = 1;

    private void getPermission() {
        int permissionCheck = ContextCompat.checkSelfPermission(context, Manifest.permission.READ_PHONE_STATE);
        Log.i(TAG, "permissionCheck" + permissionCheck);
        if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(context, new String[]{Manifest.permission.READ_PHONE_STATE}, REQUEST_READ_PHONE_STATE);
        } else {
            //TODO
            preGetToken();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
        switch (requestCode) {
            case REQUEST_READ_PHONE_STATE:
                if ((grantResults.length > 0) && (grantResults[0] == PackageManager.PERMISSION_GRANTED)) {
                    //TODO
                    preGetToken();
                }
                break;

            default:
                break;
        }
    }

    private void preGetToken() {
        //第一个参数为所需要配置的App_ID
        //第二个参数为设置的超时时间
        //第三个参数为所需实现监听回调结果接口
        Log.i(TAG, "oneLogin---->开始");
//        String appID = "6b308c4f8d1d883cb72a138e7d4ee15e";
        int timeout = 5000;
        OneLoginHelper.with().preGetToken(CUSTOM_ID, timeout, new AbstractOneLoginListener() {
            @Override
            public void onResult(JSONObject jsonObject) {
                Log.i(TAG, "预取号结果为：" + jsonObject.toString());
                try {
                    int status = jsonObject.getInt("status");
                    if (status == ONE_LOGIN_SUCCESS_STATUS) {
                        oneLoginRequestToken(promise);
                    } else {
                        Log.i(TAG, "预取号失败");
                        promise.resolve(getErrorMap(status));
                    }
                } catch (JSONException e) {
                    Log.i(TAG, "预取号失败");
                    promise.resolve(getErrorMap(ONE_LOGIN_ERROR_STATUS));
                }
            }
        });
    }

    private WritableMap getErrorMap(int status) {
        WritableMap map = Arguments.createMap();

        map.putInt("status", status);
        return map;
    }

    /**
     * 配置页面布局
     *
     * @return config
     */
    private OneLoginThemeConfig initConfig() {
        return new OneLoginThemeConfig.Builder()
                .setStatusBar(0xFFFEE333, 0x00000000, true)
                .setAuthNavLayout(0xFF3973FF, 0, true, false)
                .setLogoImgView("one_login_logo", 0, 0, true, 0, 0, 0)
                .setNumberView(0xFF3C3C3C, 14, 292, 0, 0)
                .setLogBtnLayout("one_login_shape_corner", 262, 55, 344, 0, 0)
                .setSwitchView("切换手机号", 0xFF3C3C3C, 12, false, 419, 0, 0)
                .setLogBtnTextView("登录", 0xFFFFFFFF, 14)
                .setLogBtnLoadingView("umcsdk_load_dot_white", 20, 20, 12)
                .setPrivacyCheckBox("one_login_unchecked", "one_login_checked", true, 16, 16)
                .setPrivacyClauseText("《人职初条款》", this.agreementCustom, "", "", "", "")
                .setPrivacyLayout(256, 0, 38, 0, true)
                .setPrivacyClauseView(0xFF3C3C3C, 0xFF3C3C3C, 12)
                .setPrivacyTextView("登录即同意", "和", "、", "并且授权人职初获取本机号码登录")
                //0.7.0之后新增 设置字体相关
                .setAuthNavTextViewTypeface(Typeface.DEFAULT, Typeface.DEFAULT)
                .setNumberViewTypeface(Typeface.DEFAULT)
                .setSwitchViewTypeface(Typeface.DEFAULT)
                .setLogBtnTextViewTypeface(Typeface.DEFAULT)
                .setSloganViewTypeface(Typeface.DEFAULT)
                .setPrivacyClauseViewTypeface(Typeface.DEFAULT, Typeface.DEFAULT)
                //0.8.0之后新增 设置点击提示toast文字
                .setPrivacyUnCheckedToastText("请同意服务条款")
                .build();
    }

    /**
     * 自定义控件
     */
    private void initView() {
        Button mTitleBtn = new Button(context);
        mTitleBtn.setText("其他");
        mTitleBtn.setTextColor(0xff000000);
        mTitleBtn.setTextSize(TypedValue.COMPLEX_UNIT_SP, 14);
        mTitleBtn.setBackgroundColor(Color.TRANSPARENT);
        RelativeLayout.LayoutParams mLayoutParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
        mLayoutParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, RelativeLayout.TRUE);
        mTitleBtn.setLayoutParams(mLayoutParams);


        Button mBtn = new Button(context);
        mBtn.setText("其他方式登录");
        mBtn.setTextColor(0xff3a404c);
        mBtn.setBackgroundColor(Color.TRANSPARENT);
        mBtn.setTextSize(TypedValue.COMPLEX_UNIT_SP, 13);
        RelativeLayout.LayoutParams mLayoutParams1 = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
        mLayoutParams1.addRule(RelativeLayout.CENTER_HORIZONTAL, RelativeLayout.TRUE);
        mLayoutParams1.setMargins(0, dip2px(context, 400), 0, 0);
        mBtn.setLayoutParams(mLayoutParams1);


        OneLoginHelper.with().addOneLoginRegisterViewConfig("title_button", new AuthRegisterViewConfig.Builder()
                .setView(mTitleBtn)
                .setRootViewId(AuthRegisterViewConfig.RootViewId.ROOT_VIEW_ID_TITLE_BAR)
                .setCustomInterface(new CustomInterface() {
                    @Override
                    public void onClick(Context context) {
                        Toast.makeText(context, "动态注册的其他按钮", Toast.LENGTH_SHORT).show();
                    }
                })
                .build()
        ).addOneLoginRegisterViewConfig("text_button", new AuthRegisterViewConfig.Builder()
                .setView(mBtn)
                .setRootViewId(AuthRegisterViewConfig.RootViewId.ROOT_VIEW_ID_BODY)
                .setCustomInterface(new CustomInterface() {
                    @Override
                    public void onClick(Context context) {
                        Toast.makeText(context, "动态注册的其他登录按钮", Toast.LENGTH_SHORT).show();
                    }
                })
                .build()
        );
    }

    /**
     * 定义的第三方登录设置
     */
    private void initLogin() {
        LayoutInflater inflater1 = LayoutInflater.from(this.getCurrentActivity());
        RelativeLayout relativeLayout = (RelativeLayout) inflater1.inflate(R.layout.relative_item_view, null);
        RelativeLayout.LayoutParams layoutParamsOther = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
        layoutParamsOther.addRule(RelativeLayout.CENTER_HORIZONTAL);
        relativeLayout.setLayoutParams(layoutParamsOther);
        OneLoginHelper.with().addOneLoginRegisterViewConfig("title_button", new AuthRegisterViewConfig.Builder()
                        .setView(relativeLayout)
                        .setRootViewId(AuthRegisterViewConfig.RootViewId.ROOT_VIEW_ID_BODY)
//                .setCustomInterface(new CustomInterface() {
//                    @Override
//                    public void onClick(Context context) {
//                        ToastUtils.toastMessage(context, "动态注册的其他按钮");
//                    }
//                })
                        .build()
        );
    }

    /**
     * 取号接口
     */
    private void oneLoginRequestToken(Promise promise) {
        Log.i(TAG, "开始取号");
        initLogin();
        OneLoginHelper.with().requestToken(initConfig(), new AbstractOneLoginListener() {
            //        OneLoginHelper.with().requestToken(new OneLoginThemeConfig.Builder().build(), new AbstractOneLoginListener() {
            @Override
            public void onResult(final JSONObject jsonObject) {
                Log.i(TAG, "取号结果为：" + jsonObject.toString());
                try {
                    int status = jsonObject.getInt("status");
                    if (status == ONE_LOGIN_SUCCESS_STATUS) {
                        final String process_id = jsonObject.getString("process_id");
                        final String token = jsonObject.getString("token");


                        Log.i(TAG, process_id);
                        Log.i(TAG, token);
                        OneLoginHelper.with().dismissAuthActivity();
                        WritableMap map = Arguments.createMap();
                        map.putInt("status", ONE_LOGIN_SUCCESS_STATUS);
                        map.putString("token", token);
                        map.putString("processID", process_id);
                        if (jsonObject.has("authcode")) {
                            final String authcode = jsonObject.getString("authcode");
                            map.putString("authCode", authcode);
                        }
                        promise.resolve(map);
                    } else {
                        OneLoginHelper.with().dismissAuthActivity();
//                        ToastUtils.toastMessage(context, "取号失败");
                        int errorCode = jsonObject.getInt("errorCode");
                        if (status == ONE_LOGIN_ERROR_STATUS && (errorCode == -20301 || errorCode == -20302)) {
                            promise.resolve(getErrorMap(ONE_LOGIN_BACK_STATUS));
                        } else {
                            promise.resolve(getErrorMap(status));
                        }

                    }
                } catch (JSONException e) {
                    OneLoginHelper.with().dismissAuthActivity();
//                    ToastUtils.toastMessage(context, "取号失败");
                    promise.resolve(getErrorMap(ONE_LOGIN_ERROR_STATUS));
                }
            }
        });
    }

    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }
}
